#!/usr/bin/env python
#coding=utf-8

import time
from flask import session, request, redirect, url_for, render_template, make_response, current_app
from codingabc.helpers import get_count, toint
from app.models.user import User
from app.models.role import Role, RoleMenu
from app.models.menu import Menu
from app.services.user import UserService
from app.helpers.common import request_url_str
from codingabc.database import db
from app import views


# 项目app名称
DEFAULT_APP_NAME = 'app'

# modules
DEFAULT_MODULES = (
    (views.index,         ''),
    (views.user,          '/user'),
    (views.power,         '/power'),
    (views.sys,           '/sys'),
    (views.crontab,       '/crontab'),
    (views.account,       '/account'),
)

def configure_before_handlers(app):

    @app.before_request
    def authenticate():

        # 排除校验的endpoint和static
        endpoint = request.endpoint
        if (endpoint in ('index.welcome', 'index.signin', 'index.signout', 'index.getcode','index.forget_password', 'index.get_verify_code','crontab.order_finish', 'crontab.dump_database', 'crontab.happiness', 'crontab.database_clear')
                    or request.path.find('/static') == 0):
            return

        admin_id = toint(session.get('admin_id', '0'))
        role_id  = toint(session.get('role_id', '0'))
        uid      = toint(session.get('uid', '0'))
        if admin_id <= 0 or role_id <= 0 or uid <= 0:
            print (u"### admin_id:%s, role_id:%s, uid:%s"%(admin_id, role_id, uid))
            return redirect(url_for('index.signin'))

        if endpoint and endpoint not in ['user.change_role', 'user.index']:
            url_str = request_url_str()
            is_menu_request = Menu.query.filter(Menu.endpoint == url_str).first()
            if role_id > 1 and is_menu_request:
                print (u"### endpoint:%s, role_id:%s, url_str:%s"%(endpoint, role_id, url_str))
                # # 获取用户权限
                permission = db.session.query(RoleMenu).\
                                filter(RoleMenu.role_id == Role.role_id).\
                                filter(RoleMenu.menu_id == Menu.menu_id).\
                                filter(RoleMenu.role_id == role_id).\
                                filter(Menu.endpoint == url_str).first()

                print ('### permission ==> %s'% permission)
                if not permission:
                    return u'您没有访问权限，如需访问请联系超级管理员。'


def configure_errorhandlers(app):
    """ Configures the error handlers """
    @app.errorhandler(403)
    def forbidden_page(error):
        return make_response(render_template("errors/error_img.html", error=error, error_type=403))

    @app.errorhandler(404)
    def page_not_found(error):
        return make_response(render_template("errors/error_img.html", error=error,error_type=404))

    @app.errorhandler(500)
    def server_error_page(error):
        return make_response(render_template("errors/error_img.html", error=error, error_type=500))
